package com.oceansoft.mobile.biz.admin.service;

import static com.oceansoft.mobile.common.Constant.BIZ_FILE_PATH_PREFIX;
import static com.oceansoft.mobile.common.Constant.DB_OPER_ONE_SUCC;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.oceansoft.mobile.biz.admin.entity.Merchant;
import com.oceansoft.mobile.common.Constant;
import com.oceansoft.mobile.common.base.entity.Pager;
import com.oceansoft.mobile.common.base.entity.Query;
import com.oceansoft.mobile.common.base.entity.Result;
import com.oceansoft.mobile.common.dao.ICommonDao;
import com.oceansoft.mobile.weixin.entity.WxToken;

@Service
public class MerchantServiceImpl implements IMerchantService {
	@Resource
	private ICommonDao commonDao;
	
	public Pager<Merchant> queryPageQuestions(Query query) {
		query.setSort(query.getSort());
        String page_sql = String.format("select * from t_merchant %s ", Query.getPageSQL("T", query));
        String count_sql = String.format("SELECT count(*) FROM t_merchant %s", Query.getCountSQL("T", query));
        List<Merchant> list = commonDao.loadList(page_sql, Merchant.getMapp());
        long total = commonDao.getCount(count_sql);
        return new Pager<Merchant>(total, query.getPage(), list);
	}

	public Merchant loadMerchantBySid(long sid) {
		return commonDao.loadOne("SELECT t.*,t2.theme_id themeId FROM t_merchant T LEFT JOIN t_mer_site_theme t2 ON t.sid=t2.mer_id  WHERE T.sid = ? ",
				Merchant.getFullMapp(), sid);
	}
	public int loadMerchantThemeIdBySid(long merId,String version) {
		return commonDao.getIntColumn("SELECT t.theme_id FROM t_mer_site_theme T WHERE T.mer_id = ? and t.site_type=? ", new Object[]{merId,version});
	}
	
	@Transactional
	public Result saveOrUpdatMerchant(Merchant mer) {
		int rt = DB_OPER_ONE_SUCC;
		int rt2 = DB_OPER_ONE_SUCC;
		if (null != mer) {
			if (mer.getSid() > 0) {
				rt = commonDao
						.updateOne(
								"UPDATE t_merchant SET company_name=:company_name,contact=:contact,TEL=:tel,description=:description,address=:address WHERE sid=:sid",
								mer);
				commonDao.updateColumn("t_mer_site_theme", "mer_id", mer.getSid(), "theme_id", mer.getThemeId());
			} else {
				rt = commonDao
						.saveOne(
								"INSERT INTO t_merchant (company_name,contact,tel,description,status,address) VALUES(:company_name,:contact,:tel,:description,:status,:address)",
								mer);
				long mer_id=commonDao.getPK();
				initMerchantDirtory(mer_id);
				rt2 = commonDao
						.saveOne(
								"INSERT INTO wx_token (mer_id,token,expires) VALUES(:mer_id,:token,:expires)",
								new WxToken(mer_id,java.util.UUID.randomUUID().toString().replace("-", ""),new Date().getTime()));
			}
			if (rt>0 && rt2>0)
				return new Result();
			else {
				return new Result(Result.FAILURE, "信息提交失败");
			}
		}
		return new Result(Result.FAILURE, "信息提交失败");
	}
	
	   /**
     * 初始化用户目录
     *
     * @param webRootPath 系统根目录相对于服务器绝对路径
     * @param accountId   新增商户编号
     */
    private static void initMerchantDirtory(long mer_id) {
        try {
            //            FileUtils.forceMkdir(new File(String.format("saestor://%1$s/", String.valueOf(accountId))));
        	File path=new File(Constant.PIC_BASE_PATH + File.separator + BIZ_FILE_PATH_PREFIX.replace('/', File.separatorChar) + File.separator+ String.valueOf(mer_id)+ File.separator+Constant.PIC_ART_PATH);
            FileUtils.forceMkdir(path);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("Init merchant" + mer_id + " dictory exception");
        }
    }
    
    public static void main(String[] args){
    	MerchantServiceImpl.initMerchantDirtory(1);
    }

}
